﻿using DataAccess;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MyPetHub.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Diagnostics;
using System.Diagnostics.Eventing.Reader;
using System.Linq;

namespace MyPetHub.Controllers
{
    public partial class HomeController
    {
        public async Task<IActionResult> PetStory()
        {
            await GetBannerAdvertInfo();
            await GetBlockAdvertInfo();

            //获取最多阅读故事
            var mostReadStorys = await dbContext.PetStory.OrderByDescending(x => x.readcount).Take(4).ToListAsync();
            var forJsonData = mostReadStorys.Select(x => new
            {
                src = "/file/super/imgs/" + x.coverimgsrc,
                navurl = "/Home/PetStoryContent?id=" + x.id,
                title = x.title,
                subTitle = x.subtitle
            }).ToList();
            ViewData["mostReadStorys"] = JsonConvert.SerializeObject(forJsonData, formatSettings);

            //获取最新故事
            var latestStorys = await dbContext.PetStory.OrderByDescending(x => x.updatetime).Take(8).ToListAsync();
            latestStorys = latestStorys.Where(x => !mostReadStorys.Where(s => s.id == x.id).Any()).Take(4).ToList();//排除与最多阅读重复的

            var forJsonDataLatest = latestStorys.Select(x => new
            {
                src = "/file/super/imgs/" + x.coverimgsrc,
                navurl = "/Home/PetStoryContent?id=" + x.id,
                title = x.title,
                subTitle = x.subtitle,
            }).ToList();
            ViewData["latestStorys"] = JsonConvert.SerializeObject(forJsonDataLatest, formatSettings);

            //故事集中排除的故事
            List<long> eliminatedIDs = new List<long>();
            eliminatedIDs.AddRange(mostReadStorys.Select(x => x.id).ToList());
            eliminatedIDs.AddRange(latestStorys.Select(x => x.id).ToList());
            ViewData["eliminatedIDs"] = JsonConvert.SerializeObject(eliminatedIDs, formatSettings);

            //部分页每批次获取数据量
            ViewData["perBatchCount"] = perBatchCount;
            return View();
        }

        //宠物故事批次获取
        [HttpPost]
        public async Task<IActionResult> PetStory_Partial([FromBody] object json)
        {
            JObject jobj = JObject.Parse(json.ToString());
            string searchContent = jobj["searchContent"].ToString();
            long lastPetStoryID = long.Parse(jobj["lastPetStoryID"].ToString());
            List<long> eliminatedIDs = JsonConvert.DeserializeObject<List<long>>(jobj["eliminatedIDs"].ToString()) ?? new List<long>();

            List<PetStory> pkList = null;
            if (string.IsNullOrEmpty(searchContent))
                pkList = await dbContext.PetStory.OrderBy(x => x.id).Where(x => x.id > lastPetStoryID).Take(perBatchCount + 8).ToListAsync();
            else
                pkList = dbContext.PetStory.FromSqlRaw($"select * from petstory where match(content) against('{searchContent}')").OrderBy(x => x.id).Where(x => x.id > lastPetStoryID).Take(perBatchCount + 8).ToList();

            pkList = pkList.Where(x => !eliminatedIDs.Where(s => s == x.id).Any()).Take(perBatchCount).ToList();//排除最多阅读和最新故事

            List<PetStoryModel> rpkmList = new List<PetStoryModel>();
            foreach (PetStory item in pkList)
            {
                PetStoryModel obj = new PetStoryModel();
                obj.id = item.id;
                obj.imgurl = item.coverimgsrc;
                obj.title = item.title;
                obj.subtitle = item.subtitle;
                obj.species = speciesinfoDict[item.speciesid ?? 1];
                rpkmList.Add(obj);
            }

            return View(rpkmList);
        }

        //宠物故事内容
        [HttpGet]
        public async Task<IActionResult> PetStoryContent()
        {
            long id = long.Parse(Request.Query["id"].ToString());
            var petStory = await dbContext.PetStory.Where(x => x.id == id).FirstOrDefaultAsync();
            if (petStory == null)
            {
                throw new Exception("数据不存在" + id);
            }

            await GetBlockAdvertInfo();
            await LogPetStoryAccessCount(id);

            var petStorys = await dbContext.PetStory.FromSqlRaw($"select * from petstory where match(content) against('{petStory.title}')").OrderBy(x => x.id).Take(5).ToListAsync();
            petStorys = petStorys.Where(x => x.id != petStory.id).Take(4).ToList();//排除当前故事
            ViewData["SimilarStories"] = petStorys;
            return View(petStory);
        }

        //记录宠物故事访问次数
        public async Task LogPetStoryAccessCount(long dataID)
        {
            ReadCountHeap? rchObj = await dbContext.ReadCountHeap.Where(x => x.merchantid == -1 && x.id == dataID).FirstOrDefaultAsync();
            if (rchObj != null)
            {
                rchObj.readcount += 1;
                if (rchObj.readcount >= accessCountHeap)
                {
                    var statObj = await dbContext.StatisticsInfo.Where(x => x.id == 2).FirstOrDefaultAsync();
                    statObj.readcount += rchObj.readcount;

                    var psObj = await dbContext.PetStory.Where(x => x.id == dataID).FirstOrDefaultAsync();
                    psObj.readcount += rchObj.readcount;

                    rchObj.readcount = 0;
                }
            }
            else
            {
                ReadCountHeap newRchObj = new ReadCountHeap();
                newRchObj.merchantid = -1;
                newRchObj.id = dataID;
                newRchObj.readcount = 1;
                await dbContext.ReadCountHeap.AddAsync(newRchObj);
            }

            await dbContext.SaveChangesAsync();
        }
    }
}
